<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 社团子管理
 *
 * @icon fa fa-circle-o
 */
class ClubDtl extends Backend
{

    /**
     * Club_dtl模型对象
     * @var \app\admin\model\ClubDtl
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ClubDtl;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $param = $this->request->param();
        $dtl_where = ' 1=1';
        if(isset($param['club_id'])&&$param['club_id']){
            $dtl_where .= ' and club_id = '.$param['club_id'];
        }
        $list = $this->model->with([
            'club' => function ($query) {
                $query->withField('name');
            },'user' => function ($query) {
                $query->withField('nickname');
            }]);
        $list = $list->where($where)->where($dtl_where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            // 如果选择了teacher_detail_id，自动填充user_id
            if (isset($params['teacher_detail_id']) && $params['teacher_detail_id']) {
                $teacherDetail = \app\admin\model\TeacherDetail::where(['id' => $params['teacher_detail_id']])->find();
                if ($teacherDetail && $teacherDetail['info_id']) {
                    $identityInfo = \app\admin\model\IdentityInfo::where(['id' => $teacherDetail['info_id']])->find();
                    if ($identityInfo && $identityInfo['user_id']) {
                        $params['user_id'] = $identityInfo['user_id'];
                    }
                }
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * Selectpage的实现方法
     * 重写以支持club_id过滤
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        
        // 获取club_id参数（从custom或直接参数）
        $club_id = null;
        if (isset($custom['club_id']) && $custom['club_id']) {
            $club_id = $custom['club_id'];
        } elseif ($this->request->request('club_id')) {
            $club_id = $this->request->request('club_id');
        }
        
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom, $club_id) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if ($k == 'club_id') {
                            // 跳过club_id，单独处理
                            continue;
                        }
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
                // 添加club_id过滤
                if ($club_id) {
                    $query->where('club_id', '=', $club_id);
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->field($field)
                ->field($fields)
                ->select();

            foreach ($datalist as $index => $item) {
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field => isset($item[$field]) ? $item[$field] : '',
                    'pid' => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
        }
        //这里一定要返回有list这个字段,total是可选的
        $result = ["total" => $total, "list" => $list];
        return json($result);
    }

    /**
     * 获取专栏教师列表
     * 根据club_two_id（子社团id）匹配TeacherDetail，显示姓名(费用)精品
     * 注意：club_dtl表的id就是club_two_id（子社团id）
     */
    public function getColumnTeachers()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        
        // 从custom参数中获取club_two_id（当前子社团id）
        $custom = $this->request->request("custom/a", []);
        $club_two_id = isset($custom['club_two_id']) ? $custom['club_two_id'] : null;
        
        // 如果没有从custom获取，尝试从URL参数获取（编辑页面）
        if (!$club_two_id) {
            $id = $this->request->request("id", null);
            if ($id) {
                $club_two_id = $id; // club_dtl表的id就是club_two_id
            }
        }
        
        // 如果还是没有，尝试从GET参数获取（selectpage可能通过GET传递）
        if (!$club_two_id) {
            $id = $this->request->get("id", null);
            if ($id) {
                $club_two_id = $id;
            }
        }
        
        if (!$club_two_id) {
            $this->success('',null, ['total' => 0, 'rows' => []]);
        }
        
        // 查询流程：
        // 1. 根据club_two_id查找TeacherDetail表，匹配club_two_id字段
        // 2. 通过TeacherDetail的info_id关联IdentityInfo获取姓名
        // 3. 显示格式：姓名(费用)精品
        
        $teacherDetail_list = \app\admin\model\TeacherDetail::where('club_two_id', $club_two_id)
            ->with(['identity'])
            ->select();

        if (!$teacherDetail_list || empty($teacherDetail_list)) {
            $this->success('',null, ['total' => 0, 'rows' => []]);
        }

        $arr = [];
        foreach ($teacherDetail_list as $k=>$v){
            $arr[$k]['id'] = $v['id'];
            $arr[$k]['teacher_detail_id'] = $v['id'];
            
            // 获取教师姓名
            $teacher_name = '';
            if(isset($v['identity']) && isset($v['identity']['name'])){
                $teacher_name = $v['identity']['name'];
            }
            
            // 格式化显示：姓名(费用)精品
            $arr[$k]['name'] = $teacher_name;
            $arr[$k]['hourly_rate'] = '(费用:'.$v['hourly_rate'].')';
            if($v['is_premium']){
                $arr[$k]['is_premium'] = '--精品';
            }else{
                $arr[$k]['is_premium'] = '';
            }
        }
        // 返回格式符合selectpage的要求
        $data = [
            'rows'=>$arr,
            'total'=>count($arr)
        ];
        return json($data);
    }
}
